//
//  AppDelegate.m
//  RONGAO
//
//  Created by wei wang on 2017/2/21.
//  Copyright © 2017年 wei wang. All rights reserved.
//

#import "AppDelegate.h"
#import "YTKNetworkConfig.h"
#import <AudioToolbox/AudioToolbox.h>
#import "MyCamera.h"
#include <notify.h>
#import "DTCSharePlatformManager.h"

#import "XGPush.h"
#import "XGSetting.h"
#import "CommonHttp.h"
#import "MyServerDefined.h"
#import "NSObject+FIDProperty.h"

#import "CoreJPush.h"
#import "JushModel.h"
#define NotificationLock CFSTR("com.apple.springboard.lockcomplete")
#define NotificationChange CFSTR("com.apple.springboard.lockstate")
#define NotificationPwdUI CFSTR("com.apple.springboard.hasBlankedScreen")

NSString *const kApplicationDidEnterBackground = @"Application_Did_Enter_Background";
NSString *const kApplicationWillEnterForeground = @"Application_Will_Enter_Foreground";
NSString *const kApplicationDidEnterForeground = @"Application_Did_Enter_Foreground";

#pragma mark - --------------------------锁屏判断--------------------------
static int setScreenStateCb()

{
    uint64_t locked;
    
    __block int token = 0;
    
    notify_register_dispatch("com.apple.springboard.lockstate",&token,dispatch_get_main_queue(),^(int t){
        
    });
    
    notify_get_state(token, &locked);
    
    NSLog(@"setScreenStateCb locked:%d",(int)locked);
    
    if (locked > 0) {
        
        
        
        //abort();
        ////exit(0);
    }
    
    return (int)locked;
}

static void screenLockStateChanged(CFNotificationCenterRef center,void* observer,CFStringRef name,const void* object,CFDictionaryRef userInfo)

{
    
    NSString* lockstate = (__bridge NSString*)name;
    
    if ([lockstate isEqualToString:(__bridge  NSString*)NotificationLock]) {
        
        NSLog(@"screenLockStateChanged       locked.");
        
        //abort();
        
    } else {
        
        NSLog(@"screenLockStateChanged       lock state changed.");
        
    }
    
}

@interface AppDelegate ()<MyCameraDelegate>

@end

@implementation AppDelegate
@synthesize isLoadOverDataBase;
@synthesize isRunningConnectingThread;
@synthesize connectThread;
@synthesize connectThreadLock;

@synthesize isRunningStartingThread;
@synthesize startThread;
@synthesize startThreadLock;
@synthesize showViewUID;

#pragma mark - --------------------------获取当前的语言--------------------------
- (NSString *)getPreferredCurrentLanguage
{
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    
    NSLog(@"当前语言:%@", preferredLang);
    
    return preferredLang;
    
}

#pragma mark - AudioSession implementations
void interruptionListener(void * inClientData, UInt32 inInterruptionState) {
    
    if (inInterruptionState == kAudioSessionBeginInterruption) {
        
        NSLog(@"AudioSession Begin Interruption");
    }
    else if (inInterruptionState == kAudioSessionEndInterruption) {
        
        NSLog(@"AudioSession End Interruption");
    }
}

- (void)initAudioSession {
    
    OSStatus error = AudioSessionInitialize(NULL, NULL, interruptionListener, (__bridge void *)(self));
    
    if (error) {
        printf("ERROR INITIALIZING AUDIO SESSION! %d/n", (int)error);
    }
}


- (void)pushRegisterMyServer {
    
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSArray * allLanguages = [defaults objectForKey:@"AppleLanguages"];
    NSString * preferredLang = [allLanguages objectAtIndex:0];
    NSLog(@"当前语言:%@", preferredLang);
    
    NSString *lang = preferredLang;
    NSInteger lan = 0;
    //if([lang isEqualToString:@"zh-Hans"] || [lang isEqualToString:@"zh-Hant"]) {
    if(([lang rangeOfString:@"zh-Hans"].location != NSNotFound) ||
       ([lang rangeOfString:@"zh-Hant"].location != NSNotFound)) {
        lan = 1;
    } else {
        lan = 2;
    }
    NSLog(@"lang:%@, lan:%ld", lang, (long)lan);
    
    
    //系统时区
    NSTimeZone *systemTimeZone = [NSTimeZone systemTimeZone];
    NSInteger offsetSecondsFromGMT = [systemTimeZone secondsFromGMT];
    NSLog(@"systemTimeZone:%@     offsetSecondsFromGMT:%ld",systemTimeZone, (long)offsetSecondsFromGMT);
    ;
    
    if (0 == offsetSecondsFromGMT) {
        offsetSecondsFromGMT = 1;
    }
    
    
    //#if defined(DEBUG)
    //    NSString *param = [NSString stringWithFormat:@"cmd=regalarm&token=%@&ostype=%@&lang=%ld&pushenv=%d&tzsec=%ld&appn=%@", deviceTokenString, @"ios", (long)lan, 1, (long)offsetSecondsFromGMT, XG_APPN_STR];
    //#else
    NSString *param = [NSString stringWithFormat:@"cmd=regalarm&token=%@&ostype=%@&lang=%ld&tzsec=%ld&appn=%@", self.deviceTokenString, @"ios", (long)lan, (long)offsetSecondsFromGMT, XG_APPN_STR];
    //    NSString *param = [NSString stringWithFormat:@"cmd=regalarm&token=%@&ostype=%@&lang=%ld&appn=%@", self.deviceTokenString, @"ios", (long)lan, XG_APPN_STR];
    //#endif
    
    NSString *cmd = [NSString stringWithFormat:@"%@?%@", SZY, param];
    NSLog(@"cmd:%@", cmd);
    
    CommonHttp *commonHttp = [[CommonHttp alloc] init];
    
#if 0
    NSString *mycmd = [[NSString alloc] initWithFormat:@"cmd=%@", @"regalarm"];
    NSLog(@"mycmd:%@", mycmd);
    NSString *ltoken = [[NSString alloc] initWithFormat:@"token=%@", deviceTokenString];
    NSLog(@"ltoken:%@", ltoken);
    NSString *ostype = [[NSString alloc] initWithFormat:@"ostype=%@", @"ios"];
    NSLog(@"ostype:%@", ostype);
    
    NSString *post = [[NSString alloc]initWithFormat:@"%@&%@&%@", mycmd, ltoken, ostype];
    NSLog(@"post:%@", post);;
    
    NSData *postData=[post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    
    NSData *recervedData = [commonHttp reqHttp:SZY data:postData];
#else
    NSData *recervedData;
    recervedData = [commonHttp reqHttpGetMode:cmd];
#endif
    
    NSString *servercmd = @"";
    NSString *servercode = @"";
    NSString *servermsg = @"";
    if (recervedData) {
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:recervedData options:0 error:nil];
        
        servercmd = [jsonData objectForKey:@"cmd"];
        servercode = [jsonData objectForKey:@"code"];
        servermsg = [jsonData objectForKey:@"msg"];
        
        NSLog(@"cmd=%@ code=%@, msg=%@", servercmd, servercode, servermsg);
    } else {
        NSLog(@"pushRegister recervedData == nil");
    }
    
    if (![commonHttp retValueShow:[servercmd intValue] code:[servercode intValue]]) {
        return;
    }
    
    
}



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    [[IQKeyboardManager sharedManager]setEnable:YES];
    self.camera_list = [[NSMutableArray alloc] init];
    self.camera_uid_list = [[NSMutableArray alloc] init];
    
    self.visitingMessageViewController = [[VisitingMessageViewController alloc] initWithNibName:@"VisitingMessageViewController" bundle:nil];
    self.visitingMessageViewController.hidesBottomBarWhenPushed = YES;
    
    
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    [self setNetworkBaseConfig];
    
    [self setCamP2P];
    
    [self setRootViewController];
    [self setDTSDKManagerConfig];
    
    

    application.applicationIconBadgeNumber = 0;
    
#pragma mark - --------------------------摄像头通知部分--------------------------
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(P2PPushUpdateDelegateNotification:) name:@"P2PPushUpdateDelegateNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(GetPushNotification:) name:@"GetPushNotification" object:nil];
    
    [self xingeInit:application didFinishLaunchingWithOptions:launchOptions];
    
    
    [CoreJPush registerJPush:launchOptions];
    
    
    
    
    [self shareSDK];
    
    
    return YES;
    
}


- (void)xingeInit:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    
    
    [XGPush startApp:2200257489 appKey:@"IW748P64SDGS"];
    //    [XGPush startApp:2200260476 appKey:@"I97WR2K62PLT"];
    //注销之后需要再次注册前的准备
    void (^successCallback)(void) = ^(void){
        //如果变成需要注册状态
        if(![XGPush isUnRegisterStatus])
        {
            //iOS8注册push方法
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
            
            float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
            if(sysVer < 8){
                [self registerPush];
            }
            else{
                [self registerPushForIOS8];
            }
#else
            //iOS8之前注册push方法
            //注册Push服务，注册后才能收到推送
            [self registerPush];
#endif
        }
    };
    [XGPush initForReregister:successCallback];
    
    // [XGPush registerPush];  //注册Push服务，注册后才能收到推送
    
    
    //推送反馈(app不在前台运行时，点击推送激活时)
    //[XGPush handleLaunching:launchOptions];
    
    //推送反馈回调版本示例
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]handleLaunching's successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]handleLaunching's errorBlock");
    };
    
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    //清除所有通知(包含本地通知)
    //[[UIApplication sharedApplication] cancelAllLocalNotifications];
    
    [XGPush handleLaunching:launchOptions successCallback:successBlock errorCallback:errorBlock];
    
    
}
- (void)registerPushForIOS8{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    
    //Types
    UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    
    //Actions
    UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];
    
    acceptAction.identifier = @"ACCEPT_IDENTIFIER";
    acceptAction.title = @"Accept";
    
    acceptAction.activationMode = UIUserNotificationActivationModeForeground;
    acceptAction.destructive = NO;
    acceptAction.authenticationRequired = NO;
    
    //Categories
    UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];
    
    inviteCategory.identifier = @"INVITE_CATEGORY";
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextDefault];
    
    [inviteCategory setActions:@[acceptAction] forContext:UIUserNotificationActionContextMinimal];
    
    NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];
    
    
    UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
    
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
}

- (void)registerPush{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}


-(void)applicationDidEnterBackground:(UIApplication *)application{
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:1];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    application.applicationIconBadgeNumber = 0;
    
    NSLog(@"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  XG_PUSH didRegisterUserNotificationSettings");
    [XGPush localNotificationAtFrontEnd:notification userInfoKey:@"clockID" userInfoValue:@"myid"];
    
    //删除推送列表中的这一条
    [XGPush delLocalNotification:notification];
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"通知推送错误为: %@", error);
}


- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void (^)())completionHandler{
    
    NSLog(@"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  XG_PUSH handleActionWithIdentifier forRemoteNotification");
    
    if([identifier isEqualToString:@"ACCEPT_IDENTIFIER"]){
        NSLog(@"ACCEPT_IDENTIFIER is clicked");
    }
    
    completionHandler();
}

- (NSArray *)readMeassgeInfo{
    
    //获取Documents目录
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //还要指定存储文件的文件名称,仍然使用字符串拼接
    NSString *filePath = [docPath stringByAppendingPathComponent:@"MeasgeHistoryArray.plist"];
    
    
    //使用一个数组来接受数据
    NSArray *readArray = [NSArray arrayWithContentsOfFile:filePath];
    
    return readArray;
}


- (NSArray *)readMeassgeCount{
    
    //获取Documents目录
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //还要指定存储文件的文件名称,仍然使用字符串拼接
    NSString *filePath = [docPath stringByAppendingPathComponent:@"MeasgeHistoryCount.plist"];
    
    
    //使用一个数组来接受数据
    NSArray *readArray = [NSArray arrayWithContentsOfFile:filePath];
    
    return readArray;
    
    
}

- (void)saveMeassgeCount:(NSMutableArray *)countArray{
    
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //还要指定存储文件的文件名称,仍然使用字符串拼接
    NSString *filePath = [docPath stringByAppendingPathComponent:@"MeasgeHistoryCount.plist"];
    NSLog(@"%@",filePath);
    if ([countArray writeToFile:filePath atomically:YES]) {
        NSArray *readArray = [NSArray arrayWithContentsOfFile:filePath];
        NSLog(@"保存成功:%@",readArray);
    }
}
- (void)saveMeassgeInfo:(NSMutableArray *)saveArray{
    
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    //还要指定存储文件的文件名称,仍然使用字符串拼接
    NSString *filePath = [docPath stringByAppendingPathComponent:@"MeasgeHistoryArray.plist"];
    NSLog(@"%@",filePath);
    if ([saveArray writeToFile:filePath atomically:YES]) {
        NSArray *readArray = [NSArray arrayWithContentsOfFile:filePath];
        NSLog(@"保存成功:%@",readArray);
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    [JPUSHService handleRemoteNotification:userInfo];

    
    NSLog(@"application didReceiveRemoteNotification ");
    
    //  [[[[_rootViewController tabBar] items] objectAtIndex:1] setBadgeValue:@"!"];
    
    if ([userInfo[@"_j_business"] integerValue] > 0) {
        
        if (userInfo[@"aps"]) {
            
            JushModel *info = [JushModel yy_modelWithJSON:userInfo[@"aps"]];
            
            NSLog(@"%@",info.alert);
            
            
#pragma mark - --------------------------获取当前时间戳--------------------------
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            
            [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
            
            NSDate *datenow = [NSDate date];
            
            NSString *currentTimeString = [formatter stringFromDate:datenow];
            
            info.time = currentTimeString;
            
            
#pragma mark - --------------------------存储messageArray--------------------------
            NSMutableArray *Array =  [NSMutableArray arrayWithArray:[self readMeassgeInfo]];
            
            [Array insertObject:[info modelToDictionary] atIndex:0];
            
            [self saveMeassgeInfo:Array];
            
            
            
            //取出数据 打印
            
            NSMutableArray *countArray = [NSMutableArray arrayWithArray:[self readMeassgeCount]];
            [countArray addObject:[info modelToDictionary]];
            [self saveMeassgeCount:countArray];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"count" object:nil];
            
            
        }
        
        
        CoreJPush *jpush = [[CoreJPush alloc] init];
        [jpush didReceiveRemoteNotification:userInfo];

       
    }else{
        
        
        NSString *uid = [[userInfo objectForKey:@"aps"] objectForKey:@"uid"];
        
        NSInteger eventType = (NSInteger)[[userInfo objectForKey:@"aps"] objectForKey:@"event_type"];
        NSInteger eventTime = (NSInteger)[[userInfo objectForKey:@"aps"] objectForKey:@"event_time"];
        
        NSLog(@"userInfo:%@", userInfo);
        
        NSLog(@"eventType:%ld, eventTime:%ld", (long)eventType, (long)eventTime);
        
        //NSUInteger timeLong = [[[userInfo objectForKey:@"aps"] objectForKey:@"event_time"] longValue];
        //NSInteger typeInt = [[[userInfo objectForKey:@"aps"] objectForKey:@"event_type"] longValue];
        
        NSString *typeStr = [[userInfo objectForKey:@"aps"] objectForKey:@"event_type"];
        NSString *timeStr = [[userInfo objectForKey:@"aps"] objectForKey:@"event_time"];
        NSLog(@"typeStr:%@, timeStr:%@", typeStr, timeStr);
        
        NSInteger typeInt = [typeStr longLongValue];
        NSUInteger timeLong = [timeStr longLongValue];
        
        BOOL findFlag = NO;
        for(int i=0; i < [self.camera_list count]; i++) {
            MyCamera *camera = [self.camera_list objectAtIndex:i];
            NSString *camerauid = [self.camera_uid_list objectAtIndex:i];
            
            if ([camerauid isEqualToString:uid]) {
                
                findFlag = YES;
                
#if 0
                [camera setRemoteNotification:eventType EventTime:eventTime];
                
                if (database != NULL) {
                    if (![database executeUpdate:@"INSERT INTO event(dev_uid, event_type, event_time) VALUES(?,?,?)", camerauid, eventType, eventTime]) {
                        NSLog(@"Fail to add event to database.");
                    }
                }
#else
                if ([self checkIsSameEventForTime:timeLong type:typeInt uid:camera.uid]) {
                    NSLog(@"!!!!!!!!!!!!! SAME EVENT !!!!!!!!!!!!!");
                    
                } else {
                    [self updatePushViewAndLog:camera type:typeInt time:timeLong];
                }
#endif
                
                break;
            }
        }
        
        if (!findFlag) {
            NSLog(@"didReceiveRemoteNotification unreg_mapping uid:%@", uid);
            
            // unregister from apns server
            dispatch_queue_t queue = dispatch_queue_create("apns-reg_client", NULL);
            dispatch_async(queue, ^{
                if (true) {
                    NSError *error = nil;
                    NSString *appidString = [[NSBundle mainBundle] bundleIdentifier];
                    //NSString *hostString = @"http://push.iotcplatform.com/apns/apns.php";
                    NSString *hostString = @"http://120.26.128.42:8088/DOOR_Server/server.php";
                    NSString *argsString = @"%@?cmd=unreg_mapping&token=%@&uid=%@&appid=%@";
                    NSString *getURLString = [NSString stringWithFormat:argsString, hostString, self.deviceTokenString, uid, appidString];
                    NSString *registerResult = [NSString stringWithContentsOfURL:[NSURL URLWithString:getURLString] encoding:NSUTF8StringEncoding error:&error];
                    
                    if (error != NULL) {
                        NSLog(@"error >>>>");
                        
                        //NSLog(@"%@",[error localizedDescription]);
                    }
                    NSLog(@"didReceiveRemoteNotification registerResult:|%@|", registerResult);
                }
            });
            
        }
        
        NSLog(@"didReceiveRemoteNotification:event:%d from uid:%@ at %ld", eventType, uid, (long)eventTime);

    }
    
    
    
    
}

- (void)updatePushViewAndLog:(MyCamera *)camera
                        type:(NSInteger)type
                        time:(NSUInteger)time {
    //    [[[[_rootViewController tabBar] items] objectAtIndex:1] setBadgeValue:@"!"];
    
    [camera setRemoteNotification:type EventTime:time];
    
    
    if (self.database != NULL) {
        if (![self.database executeUpdate:@"INSERT INTO event(dev_uid, event_type, event_time) VALUES(?,?,?)", camera.uid, [NSNumber numberWithInteger:type], [NSNumber numberWithUnsignedInteger:time]]) {
            NSLog(@"Fail to add event to database.");
        }
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    
    [JPUSHService registerDeviceToken:deviceToken];

    NSLog(@"My token is: %@", deviceToken);

#if defined(TUTKPUSH)
    
    
#if defined(P2PPETWANT)
    NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken");
#else
    NSString *inDeviceTokenStr = [deviceToken description];
    NSString *tokenString = [inDeviceTokenStr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    tokenString = [tokenString stringByReplacingOccurrencesOfString:@" " withString:@""];
    deviceTokenString = [[NSString alloc] initWithString:tokenString];
    NSString *appidString = [[NSBundle mainBundle] bundleIdentifier];
    
    dispatch_queue_t queue = dispatch_queue_create("apns-reg_client", NULL);
    dispatch_async(queue, ^{
        
        NSError *error = nil;
        //NSString *hostString = @"http://push.iotcplatform.com/apns/apns.php";
        NSString *hostString = @"http://120.26.128.42:8088/DOOR_Server/server.php";
#if defined(DEBUG)
        NSString *argsString = @"%@?cmd=reg_client&token=%@&appid=%@&dev=1";
#else
        NSString *argsString = @"%@?cmd=reg_client&token=%@&appid=%@&dev=0";
#endif
        NSString *getURLString = [NSString stringWithFormat:argsString, hostString, tokenString, appidString];
        NSLog(@"%@", getURLString);
        NSString *registerResult = [NSString stringWithContentsOfURL:[NSURL URLWithString:getURLString] encoding:NSUTF8StringEncoding error:&error];
        
        if (error != NULL) {
            NSLog(@"error >>>>");
            //NSLog(@"%@",[error localizedDescription]);
        }
        NSLog(@"didRegisterForRemoteNotificationsWithDeviceToken registerResult:%@", registerResult);
    });
    
    dispatch_release(queue);
    
    /*
     NSError *error = nil;
     NSLog(@"%@", appidString);
     NSString *hostString = @"http://push.iotcplatform.com/apns/apns.php";
     NSString *argsString = @"%@?cmd=reg_client&token=%@&appid=%@";
     NSString *getURLString = [NSString stringWithFormat:argsString, hostString, tokenString, appidString];
     NSString *registerResult = [NSString stringWithContentsOfURL:[NSURL URLWithString:getURLString] encoding:NSUTF8StringEncoding error:&error];
     NSLog(@"%@ : %@", getURLString, registerResult);
     */
#endif
    
#endif
    
    
    //NSString * deviceTokenStr = [XGPush registerDevice:deviceToken];
    
    void (^successBlock)(void) = ^(void){
        //成功之后的处理
        NSLog(@"[XGPush]register successBlock");
    };
    
    void (^errorBlock)(void) = ^(void){
        //失败之后的处理
        NSLog(@"[XGPush]register errorBlock");
    };
    
    //注册设备
    [[XGSetting getInstance] setChannel:@"appStore"];
    [[XGSetting getInstance] setGameServer:@"巨峰神"];
    
    
    NSString * deviceTokenStr = [XGPush registerDevice:deviceToken successCallback:successBlock errorCallback:errorBlock];
    
    //如果不需要回调
    //[XGPush registerDevice:deviceToken];
    
    //打印获取的deviceToken的字符串
    NSLog(@"deviceTokenStr is %@",deviceTokenStr);
    
    if (deviceTokenStr) {
        self.deviceTokenString = [[NSString alloc] initWithString:deviceTokenStr];
        if (self.deviceTokenString == nil || [self.deviceTokenString isEqualToString:@""]) {
            NSLog(@"deviceTokenString:%@", self.deviceTokenString);
        } else {
            
            
            dispatch_queue_t queue = dispatch_queue_create("push_reg_myserver", NULL);
            dispatch_async(queue, ^{
                [self pushRegisterMyServer];
            });
        }
        
    }
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}


- (void)shareSDK{
    
    [DTCSharePlatformManager setShareConfig];
    
}
- (void)GetPushNotification:(NSNotification*)notification{
    
    NSLog(@"---------- GetPushNotification -------------");
    
    if (EXRACT_BOOL(LOGIN) == NO) {
        return NSLog(@"没有登录");
    }
    
    NSDictionary *nameDictionary = [notification userInfo];
    NSString *pushUid = [nameDictionary objectForKey:@"uid"];
    NSInteger pushType = (int)[nameDictionary objectForKey:@"type"];
    NSInteger pushTime = (int)[nameDictionary objectForKey:@"time"];
    NSString *pushPicn = [nameDictionary objectForKey:@"picn"];
    
    NSLog(@"pushUid:%@",
          pushUid);
    NSLog(@"pushType:%ld",
          (long)pushType);
    NSLog(@"pushTime:%ld",
          (long)pushTime);
    NSLog(@"pushPicn:%@",
          pushPicn);
    
    NSLog(@"self.showViewUID:%@", self.showViewUID);
    if (self.showViewUID.length > 0) {
        /*
         for (int i=0; i<camera_list.count; i++) {
         MyCamera *cam = (MyCamera *)[camera_list objectAtIndex:i];
         if ([cam.uid isEqualToString:self.showViewUID]) {
         NSLog(@"UID view is showing!");
         return;
         }
         }
         */
        NSLog(@"UID view is showing!");
        return;
    } else {
    }
    
    
    NSArray *keys=[NSArray arrayWithObjects:@"uid", nil];
    NSArray *objects=[NSArray arrayWithObjects:pushUid, nil];
    NSDictionary *dic=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GetPushNotificationToView" object:self userInfo:dic];
    
    
    
}




- (BOOL)getIsRecvAudioFormat:(MyCamera *)cam {
    BOOL isRecvAudioFormat = NO;
    
#if defined(AUDIO_TO_SUPPORT)
    if (cam) {
        if (cam.sessionState == CONNECTION_STATE_CONNECTED) {
            
            //if ([camera getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED)
            
            isRecvAudioFormat = cam.isRecvAudioFormat;
            
            if (isRecvAudioFormat) {
                
            } else {
                NSLog(@"IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ");
                SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                s->channel = 0;
                [cam sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                free(s);
            }
        }
    }
    
#endif
    NSLog(@"CameraListForLiveViewController isRecvAudioFormat:%d", isRecvAudioFormat);
    
    
    return isRecvAudioFormat;
}



- (void)appWillTerminateToDo:(BOOL)isSimple {
    NSLog(@"appWillTerminateToDo begin");
    
#if defined(P2PPETWANT)
    //[petWantPlistFileExternalCache release];
    petWantPlistFileExternalCache = nil;
#endif
    
    // stop record
    for (MyCamera *camera in self.camera_list) {
        if (camera.cameraLocalRecorder) {
            camera.cameraLocalRecorder.ParentID = nil;
            [camera.cameraLocalRecorder stopRecord];
        }
    }
    
    [self disLoopConnect];
    
    for (MyCamera *camera in self.camera_list) {
        if (isSimple) {
            NSLog(@"appWillTerminateToDo begin isSimple==YES");
            
        } else {
            NSLog(@"appWillTerminateToDo [camera stop:0] camera.uid:%@", camera.uid);
            [camera stop:0];
            
            NSLog(@"appWillTerminateToDo [camera disconnect] camera.uid:%@", camera.uid);
            [camera disconnect];
        }
        
    }
    
    NSLog(@"appWillTerminateToDo [MyCamera uninitIOTC]");
    [MyCamera uninitIOTC];
#if defined(P2PPETWANT) || defined(P2PNEX)
    RDT_DeInitialize();
#endif
    [self closeDatabase];
    
    //[camera_list release];
    //[device_list release];
    
    self.deviceTokenString = nil;
    self.camera_list = nil;
    self.camera_uid_list = nil;
    
    NSLog(@"appWillTerminateToDo end");
    
}

#pragma mark - AppDelegate globalDelegate
+ (AppDelegate *)globalDelegate {
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}


#pragma mark - 设置摄像头部分
- (void)setCamP2P{
    isLoadOverDataBase = NO;
    [self openDatabase];
    [self createTable];
    
    [MyCamera initIOTC];
#if defined(P2PPETWANT) || defined(P2PNEX)
    RDT_Initialize();
#endif
    
    
    [self initAudioSession];
    
    [self loadDeviceFromDatabase];
    NSLog(@"loadEventNotificationFromDatabase in");
    dispatch_queue_t queue = dispatch_queue_create("load_event_database", NULL);
    dispatch_async(queue, ^{
        NSLog(@"load_event_database begin !");
        
        [self loadEventNotificationFromDatabase];
        
        NSLog(@"load_event_database over !");
        
    });
    
    NSLog(@"loadEventNotificationFromDatabase out");
    
    [self loopConnect];
    
}

#pragma mark - SQLite Methods
- (void)openDatabase
{
    NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *databaseFilePath = [[documentsPaths objectAtIndex:0] stringByAppendingPathComponent:@"database.sqlite"];
    
    self.database = [[FMDatabase alloc] initWithPath:databaseFilePath];
    
    if ([self.database open])
        NSLog(@"open sqlite db ok.");
}

- (void)closeDatabase
{
    if (self.database != NULL) {
        [self.database close];
        NSLog(@"close sqlite db ok.");
    }
}

- (void)createTable
{
    if (self.database != NULL) {
        
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_DEVICE]) NSLog(@"Can not create table device");
        
#if defined(ACCOUNT_MODE)
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_DEVICE2]) NSLog(@"Can not create table device2");
#endif
        
#if defined(LOCAL_SOURCE2)
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_SNAPSHOT2]) NSLog(@"Can not create table snapshot2");
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_RECORD2]) NSLog(@"Can not create table record2");
#else
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_SNAPSHOT]) NSLog(@"Can not create table snapshot");
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_RECORD]) NSLog(@"Can not create table record");
#endif
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_EVENT]) NSLog(@"Can not create table event");
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_NOTIFICATION]) NSLog(@"Can not create table notification");
        
        if (![self.database executeUpdate:SQLCMD_CREATE_TABLE_REMOTE_RECORD]) NSLog(@"Can not create table remote_record");
        
        /* Edit here while table columns been modified */
        //if (![database columnExists:@"device" columnName:@""]) [database executeUpdate:@"ALTER TABLE device ADD COLUMN column-name column-type"];
    }
}

#pragma mark - 指定数据列表
- (NSMutableArray *)loadDeviceFromDatabase:(NSString *)indexView{
    
    
    NSMutableArray *array = [NSMutableArray array];
    
    if (self.database != NULL) {
        
        
        NSLog(@"=====================self.indexView:%@",indexView);
        
        //        FMResultSet *rs = [self.database executeQuery:@"SELECT * FROM device"];
        FMResultSet *rs = [self.database executeQuery:@"SELECT * FROM device WHERE indexView=?",indexView];
        
        int cnt = 0;
        
        while([rs next] && cnt++ < MAX_CAMERA_LIMIT) {
            
            NSString *uid = [rs stringForColumn:@"dev_uid"];
            NSString *name = [rs stringForColumn:@"dev_nickname"];
            NSString *view_acc = [rs stringForColumn:@"view_acc"];
            NSString *view_pwd = [rs stringForColumn:@"view_pwd"];
            NSInteger channel = [rs intForColumn:@"channel"];
            NSString *WindexView = [rs stringForColumn:@"indexView"];
            
            
            NSLog(@"Load Camera(%@, %@, %@, %@, %@)", name, uid, view_acc, view_pwd,WindexView);
            
            for (MyCamera *info in self.camera_list) {
                
                if ([info.uid isEqualToString:uid]) {
                    
                    [array addObject:info];
                }
                
            }
        }
        
        [rs close];
    }
    
    return array;
    
}
#pragma mark - 加载数据库获取摄像头列表数据
- (void)loadDeviceFromDatabase {
    
#if defined(ONLY_DEVICE)
    
#if defined(P2PCARCAM) || defined(P2PCARCAM2)
    //NSString *uid = @"59UN4R25S6ZJCNS9111A";
    NSString *uid = @"01234567890123456789";
    
    NSString *name = @"CarCam";
    NSString *view_acc = @"admin";
    NSString *view_pwd = @"123456";
    NSInteger channel = 0;
#elif defined(P2PPETWANT)
    
    NSString *uid = @"CZNT9B7Y4PBP9NPMWRX1";
    
    NSString *name = @"PetWant";
    NSString *view_acc = @"admin";
    NSString *view_pwd = @"123456";
    NSInteger channel = 0;
#else
    NSString *uid = @"01234567890123456789";
    
    NSString *name = @"IPCAM";
    NSString *view_acc = @"admin";
    NSString *view_pwd = @"123456";
    NSInteger channel = 0;
#endif
    
    NSLog(@"P2PCARCAM Load Camera(%@, %@, %@, %@)", name, uid, view_acc, view_pwd);
    
    MyCamera *camera = [[MyCamera alloc] initWithName:name viewAccount:view_acc viewPassword:view_pwd];
    [camera setLastChannel:channel];
    
    [self.camera_list addObject:camera];
    [self.camera_uid_list addObject:uid];
    
#elif defined(MULTIPLE_DEVICE)
    NSArray *nameArr = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
    NSArray *uidArr = [NSArray arrayWithObjects:@"59UN4R25S6ZJCNS9111A", @"CZNT9B7Y4PBP9NPMWRX1", @"C3HT8F6ED6ZYUH6MWRD1", @"01234567890123456790", nil];
    NSArray *accArr = [NSArray arrayWithObjects:@"admin", @"admin", @"admin", @"admin", nil];
    NSArray *pwdArr = [NSArray arrayWithObjects:@"123456", @"123456", @"123456", @"123456", nil];
    
    for (int i=0; i<uidArr.count; i++) {
        MyCamera *camera = [[MyCamera alloc] initWithName:[nameArr objectAtIndex:i] viewAccount:[accArr objectAtIndex:i] viewPassword:[pwdArr objectAtIndex:i]];
        [camera setLastChannel:0];
        
        [self.camera_list addObject:camera];
        [self.camera_uid_list addObject:[uidArr objectAtIndex:i]];
    }
    
#elif defined(ACCOUNT_MODE)
    NSLog(@"loadDeviceFromDatabase ACCOUNT_MODE");
    
    
#else
    
    if (self.database != NULL) {
        
        FMResultSet *rs = [self.database executeQuery:@"SELECT * FROM device"];
        
        int cnt = 0;
        
        while([rs next] && cnt++ < MAX_CAMERA_LIMIT) {
            
            NSString *uid = [rs stringForColumn:@"dev_uid"];
            NSString *name = [rs stringForColumn:@"dev_nickname"];
            NSString *view_acc = [rs stringForColumn:@"view_acc"];
            NSString *view_pwd = [rs stringForColumn:@"view_pwd"];
            NSInteger channel = [rs intForColumn:@"channel"];
            NSString *WindexView = [rs stringForColumn:@"indexView"];
            
#if defined(P2PNETCAM_HAIER)
            NSString *position = [rs stringForColumn:@"dev_position"];
            
            NSLog(@"Load Camera(%@, %@, %@, %@, %@ , %@)", position, name, uid, view_acc, view_pwd,indexView);
            
            MyCamera *camera = [[MyCamera alloc] initWithName:name viewAccount:view_acc viewPassword:view_pwd viewPosition:position];
            [camera setLastChannel:channel];
            
#else
            
            NSLog(@"Load Camera(%@, %@, %@, %@, %@)", name, uid, view_acc, view_pwd,WindexView);
            
            MyCamera *camera = [[MyCamera alloc] initWithName:name viewAccount:view_acc viewPassword:view_pwd];
            [camera setLastChannel:channel];
            
            
#endif
            
#if defined(P2PPUSH) || defined(SYNC_REMOTE_SERVER)
            camera.delegate3 = self;
            
#endif
            //            camera.delegate2 = self;
            
            NSLog(@"camera.delegate3 = self;%@",camera.delegate3);
            
            [self.camera_list addObject:camera];
            [self.camera_uid_list addObject:uid];
            
        }
        
        [rs close];
    }
#endif
    
    isLoadOverDataBase = YES;
}

#pragma mark - loadEventNotificationFromDatabase
#warning 这部分有问题

- (void)loadEventNotificationFromDatabase {
    
    BOOL isCheckUID = YES;
    while (isCheckUID) {
        BOOL isNull = NO;
        for (int m=0; m<[self.camera_list count]; m++) {
            MyCamera *camera = (MyCamera *)[self.camera_list objectAtIndex:m];
            if (nil == camera.uid || [camera.uid isEqualToString:@""]) {
                if (nil == camera.deviceID || [camera.deviceID isEqualToString:@""]) {
                    isNull = YES;
                    
                    break;
                }
                
            }
        }
        
        if (isNull) {
            isCheckUID = YES;
        } else {
            isCheckUID = NO;
            break;
        }
        
        //     NSLog(@"loadEventNotificationFromDatabase isCheckUID usleep(500*1000)");
        usleep(500*1000);
    }
    
    
    if (self.database != NULL) {
        
        NSMutableArray* devUidList = [[NSMutableArray alloc] init];
        NSMutableArray* notificationList = [[NSMutableArray alloc] init];
        
        NSMutableString *uidListStr = [NSMutableString stringWithCapacity:20];
        NSMutableString *aliasListStr = [NSMutableString stringWithCapacity:20];
        NSMutableString *pushmodeListStr = [NSMutableString stringWithCapacity:20];
        NSMutableString *soundnameListStr = [NSMutableString stringWithCapacity:20];
        
        
        FMResultSet *rs = [self.database executeQuery:@"SELECT * FROM notification"];
        
        while([rs next]) {
            
            NSString *uid = [rs stringForColumn:@"dev_uid"];
            NSInteger push_notification = [rs intForColumn:@"push_notification"];
            
            [devUidList addObject:uid];
            [notificationList addObject:[NSNumber numberWithInt:(int)push_notification]];
            
            NSLog(@"devUidList notificationList uid:%@, push_notification:%ld,  [camera_list count]:%ld", uid, (long)push_notification, [self.camera_list count]);
            
            
#if defined(P2PBANDIANGOU) || defined(P2PWEXVS) || defined(P2PAUROCAM_WEX)
            
#else
            for (int m=0; m<[self.camera_list count]; m++) {
                MyCamera *camera = (MyCamera *)[self.camera_list objectAtIndex:m];
                NSLog(@"camera.uid:%@, m:%d", camera.uid, m);
                
                if ([camera.uid isEqualToString:uid]) {
                    camera.isPushMode = push_notification;
                    NSLog(@"uid:%@, camera.isPushMode:%ld", uid, (long)camera.isPushMode);
                    break;
                }
            }
#endif
            
        }
        
        [rs close];
        
        
        
        
        // delete devUidList
        for (int i=0; i<[devUidList count]; i++) {
            NSString *uid = (NSString *)[devUidList objectAtIndex:i];
            NSInteger push_notification = [(NSNumber *)[notificationList objectAtIndex:i] intValue];
            NSLog(@"devUidList notificationList i=%d, uid:%@, push_notification:%ld", i, uid, (long)push_notification);
            
            NSString *alias = @"";
            NSString *soundname = @"";
            for (int k=0; k<[self.camera_list count]; k++) {
                MyCamera *camera = (MyCamera *)[self.camera_list objectAtIndex:k];
                if ([camera.uid isEqualToString:uid]) {
                    alias = camera.name;
                    soundname = camera.pushSoundName;
                    break;
                }
            }
            NSLog(@"alias:%@", alias);
            NSLog(@"soundname:%@", soundname);
            
            if (0 == i) {
                [uidListStr appendFormat:@"%@", uid];
                [aliasListStr appendFormat:@"%@", alias];
                [pushmodeListStr appendFormat:@"%ld", (long)push_notification];
                [soundnameListStr appendFormat:@"%@", soundname];
            } else {
                [uidListStr appendFormat:@":%@", uid];
                [aliasListStr appendFormat:@":%@", alias];
                [pushmodeListStr appendFormat:@":%ld", (long)push_notification];
                [soundnameListStr appendFormat:@":%@", soundname];
            }
        }
        NSLog(@"uidListStr:%@", uidListStr);
        NSLog(@"aliasListStr:%@", aliasListStr);
        NSLog(@"pushmodeListStr:%@", pushmodeListStr);
        NSLog(@"soundnameListStr:%@", soundnameListStr);
        
        NSInteger count = [devUidList count];
        NSLog(@"count:%ld", (long)count);
        if (count > 0) {
            
            dispatch_queue_t queue = dispatch_queue_create("myserver_maplist", NULL);
            dispatch_async(queue, ^{
                
                for (int i=0; i<120; i++) {
                    if (self.deviceTokenString != nil) {
                        break;
                    }
                    //          NSLog(@"loadEventNotificationFromDatabase deviceTokenString==nil");
                    usleep(500*1000);
                }
                
                if (self.deviceTokenString != nil) {
                    
#if defined(P2PBANDIANGOU) || defined(P2PWEXVS) || defined(P2PAUROCAM_WEX)
#elif defined(P2PPETWANT)
#else
                    
                    [self pushMapDeviceList:count listId:uidListStr listPushMode:pushmodeListStr listAlias:aliasListStr listSoundName:soundnameListStr];
#endif
                    
                }
                
            });
            
            
        } else {
            NSLog(@"No uid!!!");
            
            
        }
        
        
        
        
        [devUidList removeAllObjects];
        [notificationList removeAllObjects];
        
    }
}


- (void)pushMapDeviceList:(NSInteger)count listId:(NSString *)listIdStr listPushMode:(NSString *)listPushModeStr listAlias:(NSString *)listAliasStr listSoundName:(NSString *)listSoundNameStr {
    
    
    NSString *param = [NSString stringWithFormat:@"cmd=updatedev&token=%@&ostype=%@&devcount=%ld&devidlist=%@&pushallow=%@&devaliaslist=%@&soundlist=%@&appn=%@", self.deviceTokenString, @"ios", (long)count, listIdStr, listPushModeStr, listAliasStr, listSoundNameStr, XG_APPN_STR];
    
    NSString *cmd = [NSString stringWithFormat:@"%@?%@", SZY, param];
    NSLog(@"cmd:%@", cmd);
    
    NSString *dataUTF8 = [cmd stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"dataUTF8:%@", dataUTF8);
    cmd = dataUTF8;
    
    CommonHttp *commonHttp = [[CommonHttp alloc] init];
    NSData *recervedData;
    recervedData = [commonHttp reqHttpGetMode:cmd];
    
    NSString *servercmd = @"";
    NSString *servercode = @"";
    NSString *servermsg = @"";
    if (recervedData) {
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:recervedData options:0 error:nil];
        
        servercmd = [jsonData objectForKey:@"cmd"];
        servercode = [jsonData objectForKey:@"code"];
        servermsg = [jsonData objectForKey:@"msg"];
        
        NSLog(@"cmd=%@ code=%@, msg=%@", servercmd, servercode, servermsg);
    } else {
        NSLog(@"pushMapDeviceList recervedData == nil");
    }
    
    if (![commonHttp retValueShow:[servercmd intValue] code:[servercode intValue]]) {
        return;
    }
    
}



#pragma mark - Threading
- (void)loopConnect {
    self.isRunningConnectingThread = TRUE;
    
    if (connectThread == nil) {
        connectThreadLock = [[NSConditionLock alloc] initWithCondition:NOTDONE];
        connectThread = [[NSThread alloc] initWithTarget:self selector:@selector(doLoopConnect) object:nil];
        [connectThread start];
    }
    
    [self loopStart];
}

- (void)doLoopConnect {
    
    
    //usleep(500 * 1000);
    
    [connectThreadLock lock];
    
    //LOG(@"=== Connect Thread Start (%@) ===", uid);
    
#if defined(P2PNETCAM_HAIER)
    for(int i=0; i < [self.position_self.camera_list count]; i++) {
        MyCamera *camera = [self.position_self.camera_list objectAtIndex:i];
        //for (MyCamera *camera in self.position_self.camera_list) {
#else
        for(int i=0; i < [self.camera_list count]; i++) {
            MyCamera *camera = [self.camera_list objectAtIndex:i];
            NSString *camerauid = [self.camera_uid_list objectAtIndex:i];
            //for (MyCamera *camera in self.camera_list) {
#endif
            
            
            if (self.isRunningConnectingThread)
            {
                NSLog(@"1 clflvc for begin!");
                
                //[camera disconnect];
                if (camera.sessionState != CONNECTION_STATE_CONNECTED)
                    [camera connect:camerauid];
                
                usleep(LOOP_USLEEP / 100);
                
                NSLog(@"2 clflvc for end!");
            }
            else
            {
                break;
            }
        }
        
        
#if 0
        
#if defined(P2PNETCAM_HAIER)
        for(int i=0; i < [self.position_self.camera_list count]; i++) {
            MyCamera *camera = [self.position_self.camera_list objectAtIndex:i];
            //for (MyCamera *camera in self.position_self.camera_list) {
#else
            for(int i=0; i < [self.camera_list count]; i++) {
                MyCamera *camera = [self.camera_list objectAtIndex:i];
                //for (MyCamera *camera in self.camera_list) {
#endif
                if (self.isRunningConnectingThread)
                {
                    NSLog(@"3 clflvc for begin!");
                    
                    [camera start:0];
                    
                    
                    SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                    s->channel = 0;
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                    free(s);
                    
                    SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
                    free(s2);
                    
                    SMsgAVIoctrlSetTimeReq *s3 = (SMsgAVIoctrlSetTimeReq *)malloc(sizeof(SMsgAVIoctrlSetTimeReq));
                    s3->time_second_0zone_ = [[NSDate date] timeIntervalSince1970];
                    s3->diff_zone_minites_ = [[NSTimeZone localTimeZone] secondsFromGMT] / 60;
                    
                    [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_TIME_REQ Data:(char *)s3 DataSize:sizeof(SMsgAVIoctrlSetTimeReq)];
                    free(s3);
                    NSLog(@"AppDelegate.m doLoopConnect sendIOCtrlToChannel IOTYPE_USER_IPCAM_SET_TIME_REQ(uid:%@)", camera.uid);
                    
                    NSLog(@"4 clflvc for end!");
                    
                }
                else
                {
                    break;
                }
                
                ++num;
                if (LOOP_NUM == num) {
                    num = 0;
                    
                    usleep(LOOP_USLEEP);
                }
            }
            
#endif
            //LOG(@"=== Connect Thread Exit (%@) ===", uid);
            
            [connectThreadLock unlockWithCondition:DONE];
            
            
            self.isRunningConnectingThread = FALSE;
        }
        
        
#pragma mark - --------------------------横竖屏设置-------------------------
        
        - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
        {
            
            
            /* if ([[self.window.subviews.lastObject class].description isEqualToString:@"DoorSystemHomeViewController"]) {
             return UIInterfaceOrientationMaskAllButUpsideDown;
             }
             else {
             return UIInterfaceOrientationMaskPortrait;
             }
             */
            if (!self.isUIInterfaceOrientationMaskAllButUpsideDown)
            {
                return UIInterfaceOrientationMaskPortrait;
            }
            else{
                
                //  [[NSNotificationCenter defaultCenter] postNotificationName:@"getScrennState" object:nil];
                return UIInterfaceOrientationMaskAllButUpsideDown;
            }
            
        }
        
        
        - (void)disLoopConnect
        {
            NSLog(@"disLoopConnect [self disLoopStart] begin");
            
            [self disLoopStart];
            
            NSLog(@"disLoopConnect [self disLoopStart] end");
            
            if (connectThread != nil) {
                
                NSLog(@"disLoopConnect!!!!!!!!!!!");
                
                self.isRunningConnectingThread = FALSE;
                
                [connectThreadLock lockWhenCondition:DONE];
                [connectThreadLock unlock];
                
                connectThread = nil;
            }
        }
        
        - (void)loopStart {
            
            NSLog(@"AppDelegate clflvc loopStart............");
            self.isRunningStartingThread = TRUE;
            
            if (startThread == nil) {
                startThreadLock = [[NSConditionLock alloc] initWithCondition:NOTDONE];
                startThread = [[NSThread alloc] initWithTarget:self selector:@selector(doLoopStart) object:nil];
                [startThread start];
            }
        }
        
        - (void)doLoopStart {
            
            
            //usleep(500 * 1000);
            
            [startThreadLock lock];
            
            NSLog(@"=== clflvc doLoopStart Thread Waite Connect Over  ===");
            
            while(self.isRunningConnectingThread) {
                usleep(100 * 1000);
                NSLog(@"=== self.isRunningConnectingThread  usleep(100 * 1000); ===");
                continue;
            }
            
            BOOL isAllConnected = NO;
            int index = 0;
            while(!isAllConnected && [self.camera_list count] > 0) {
                for(int i=index; i < [self.camera_list count]; i++) {
                    
                    MyCamera *camera = [self.camera_list objectAtIndex:i];
                    
                    if (camera.sessionState == CONNECTION_STATE_CONNECTING) {
                        //  NSLog(@"camera(%@).sessionState == CONNECTION_STATE_CONNECTING", camera.uid);
                        
                        isAllConnected = NO;
                        index = i;
                        usleep(100 * 1000);
                        
                        break;
                    } else {
                        isAllConnected = YES;
                    }
                    
                    usleep(200 * 1000);
                    
                }
            }
            
            NSLog(@"=== clflvc doLoopStart Thread Start  ===");
            
#if defined(P2PNETCAM_HAIER)
            for(int i=0; i < [self.position_self.camera_list count]; i++) {
                MyCamera *camera = [self.position_self.camera_list objectAtIndex:i];
                //for (MyCamera *camera in self.position_self.camera_list) {
#else
                for(int i=0; i < [self.camera_list count]; i++) {
                    MyCamera *camera = [self.camera_list objectAtIndex:i];
                    //for (MyCamera *camera in self.camera_list) {
#endif
                    
                    
                    if (self.isRunningStartingThread)
                    {
                        NSLog(@"1 clflvc for begin!");
                        
                        if ([camera getConnectionStateOfChannel:0] != CONNECTION_STATE_CONNECTED) {
                            NSLog(@"([camera getConnectionStateOfChannel:0] != CONNECTION_STATE_CONNECTED)");
                            
                            [camera start:0];
                            
                            SMsgAVIoctrlGetAudioOutFormatReq *s = (SMsgAVIoctrlGetAudioOutFormatReq *)malloc(sizeof(SMsgAVIoctrlGetAudioOutFormatReq));
                            s->channel = 0;
                            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlGetAudioOutFormatReq)];
                            free(s);
                            
                            SMsgAVIoctrlGetSupportStreamReq *s2 = (SMsgAVIoctrlGetSupportStreamReq *)malloc(sizeof(SMsgAVIoctrlGetSupportStreamReq));
                            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ Data:(char *)s2 DataSize:sizeof(SMsgAVIoctrlGetSupportStreamReq)];
                            free(s2);
                            
                            SMsgAVIoctrlSetTimeReq *s3 = (SMsgAVIoctrlSetTimeReq *)malloc(sizeof(SMsgAVIoctrlSetTimeReq));
                            s3->time_second_0zone_ = [[NSDate date] timeIntervalSince1970];
                            s3->diff_zone_minites_ = [[NSTimeZone localTimeZone] secondsFromGMT] / 60;
                            
                            [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_TIME_REQ Data:(char *)s3 DataSize:sizeof(SMsgAVIoctrlSetTimeReq)];
                            free(s3);
                            NSLog(@"AppDelegate.m doLoopStart sendIOCtrlToChannel IOTYPE_USER_IPCAM_SET_TIME_REQ(uid:%@)", camera.uid);
                            
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU)
                            [self armingSMsgAVIoctrlGet:camera];
#endif
                            
#if defined(P2PMONITOR_LAMP)|| defined(P2PVIDEODB)
                            [self ledSMsgAVIoctrlGet:camera];
#endif
                            
#if defined(P2PNEX)
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                [self getDeviceAboutInfo:camera];
                            });
#endif
                            
                        }
                        
                        usleep(LOOP_USLEEP / 100);
                        
                        NSLog(@"2 clflvc for end!");
                    }
                    else
                    {
                        break;
                    }
                }
                
                NSLog(@"=== clflvc doLoopStart Thread Exit ===");
                
                [startThreadLock unlockWithCondition:DONE];
                
                
                self.isRunningStartingThread = FALSE;
            }
            
            
            
            - (void)disLoopStart
            {
                if (startThread != nil) {
                    
                    NSLog(@"clflvc disLoopStart!!!!!!!!!!!");
                    
                    self.isRunningStartingThread = FALSE;
                    
                    [startThreadLock lockWhenCondition:DONE];
                    
                    NSLog(@"clflvc 2 disLoopStart!!!!!!!!!!!");
                    
                    [startThreadLock unlock];
                    
                    startThread = nil;
                }
            }
            
            
            - (void)applicationWillTerminate:(UIApplication *) application
            {
                NSLog(@"applicationWillTerminate");
                
                [self appWillTerminateToDo:NO];
                
                [UIApplication sharedApplication].idleTimerDisabled = NO;
            }
            
            
#pragma mark - 摄像头通知处理部分
            
            - (void)P2PPushUpdateDelegateNotification:(NSNotification*)notification {
                NSLog(@"P2PPushUpdateDelegateNotification notification:%@", notification);
                if (self.camera_list) {
                    for(int i=0; i<self.camera_list.count; i++) {
                        MyCamera *cam = (MyCamera *)[self.camera_list objectAtIndex:i];
                        
                        cam.delegate3 = self;
                    }
                }
            }
            
            
            
#if defined(P2PMONITOR_LAMP)|| defined(P2PVIDEODB)
            - (void)ledSMsgAVIoctrlGet:(MyCamera *)camera
            {
                NSLog(@"armingSMsgAVIoctrlGet");
                SMsgAVIoctrlThirdpartReq *structArming = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
                memset(structArming, 0, sizeof(SMsgAVIoctrlThirdpartReq));
                
                structArming->command_types_ = THIRD_PART_GET_LED_STATUS;
                
                [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ Data:(char *)structArming DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
                free(structArming);
            }
            
            - (void)ledSMsgAVIoctrlSet:(MyCamera *)camera
            {
                SMsgAVIoctrlThirdpartReq *s = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
                memset(s, 0, sizeof(SMsgAVIoctrlThirdpartReq));
                
                s->command_types_ = THIRD_PART_SET_LED_STATUS;
                s->value1_ = (int)camera.newContrlValue1;
                
                [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ Data:(char *)s DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
                
                free(s);
                
            }
#endif
            
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PVIDEODB)
#pragma mark - get set arming or disarming
            - (void)armingSMsgAVIoctrlGet:(MyCamera *)camera
            {
                SMsgAVIoctrlThirdpartReq *structArming = (SMsgAVIoctrlThirdpartReq *)malloc(sizeof(SMsgAVIoctrlThirdpartReq));
                memset(structArming, 0, sizeof(SMsgAVIoctrlThirdpartReq));
                
                structArming->command_types_ = THIRD_PART_GET_ALARMED_STATUS;
                
                [camera sendIOCtrlToChannel:0
                                       Type:IOTYPE_USER_IPCAM_THIRDPART_SETTING_REQ
                                       Data:(char *)structArming
                                   DataSize:sizeof(SMsgAVIoctrlThirdpartReq)];
                free(structArming);
            }
#endif
            
            - (void)getDeviceAboutInfo:(MyCamera *)cam {
                NSLog(@"getDeviceAboutInfo cam.uid:%@", cam.uid);
                
                SMsgAVIoctrlDeviceInfoReq *s = (SMsgAVIoctrlDeviceInfoReq *)malloc(sizeof(SMsgAVIoctrlDeviceInfoReq));
                memset(s, 0, sizeof(SMsgAVIoctrlDeviceInfoReq));
                
                [cam sendIOCtrlToChannel:0
                                    Type:IOTYPE_USER_IPCAM_DEVINFO_REQ
                                    Data:(char *)s
                                DataSize:sizeof(SMsgAVIoctrlDeviceInfoReq)];
                free(s);
            }
            
            - (double)getTimeInMillis:(STimeDay)time {
                
                double result;
                
                NSDateComponents *comps = [[NSDateComponents alloc] init];
                
                [comps setYear:time.year];
                [comps setMonth:time.month];
                [comps setWeekday:time.wday];
                [comps setDay:time.day];
                [comps setHour:time.hour];
                [comps setMinute:time.minute];
                [comps setSecond:time.second];
                
                
                NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
                [cal setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
                [cal setLocale:[NSLocale currentLocale]];
                
                NSDate *date = [cal dateFromComponents:comps];
                
                result = [date timeIntervalSince1970];
                
                
                
                return result;
            }
            
            
            
            
#pragma mark - MyCameraDelegate Methods
            - (void)camera:(MyCamera *)camera_ _didChangeSessionStatus:(NSInteger)status
            {
                NSLog(@"######################################### _didChangeSessionStatus camera_.uid:%@, status:%lx", camera_.uid, (long)status);
                
                
#if defined(SYNC_REMOTE_SERVER)
                
#endif
                
                
            }
            
            
            - (void)camera:(MyCamera *)camera_ _didChangeChannelStatus:(NSInteger)channel ChannelStatus:(NSInteger)status
            {
                NSLog(@"######################################### _didChangeChannelStatus camera_.uid:%@, channel:%ld, status:%lx", camera_.uid, (long)channel, (long)status);
                
#if defined(SYNC_REMOTE_SERVER)
                if (camera_.sessionState == CONNECTION_STATE_CONNECTED && [camera_ getConnectionStateOfChannel:0] == CONNECTION_STATE_CONNECTED) {
                    
                    if (1 != camera_.isProcessRemoteServer) {
                        camera_.isProcessRemoteServer = 1;
                        
                        // get device flag
                        
                        [self sendMsgToGetDeviceFlageFromDevice:camera_];
                        
                    }
                    
                    
                }
#endif
                
            }
            
            - (void)camera:(MyCamera *)camera_ _didReceiveIOCtrlWithType:(NSInteger)type Data:(const char *)data DataSize:(NSInteger)size {
                
                NSLog(@"****************************************** AppDelegate camera_.uid:%@, type:%lx", camera_.uid, (long)type);
                
                if(IOTYPE_USER_IPCAM_EVENT_REPORT == type) {
                    NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT == type");
                    
                    NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT camera_.uid:%@", camera_.uid);
                    
                    SMsgAVIoctrlEvent *s = (SMsgAVIoctrlEvent *)data;
                    
                    NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->event:%d", s->event);
                    NSLog(@"IOTYPE_USER_IPCAM_EVENT_REPORT s->time:%d", s->time);
                    
                    
                    long eventTime = s->time;
                    if (eventTime <= 0) {
                        eventTime = [self getTimeInMillis:s->stTime];
                    }
                    NSLog(@"eventTime:%ld", eventTime);
                    
                    if ([self checkIsSameEventForTime:eventTime type:s->event uid:camera_.uid]) {
                        NSLog(@"!!!!!!!!!!!!! SAME EVENT !!!!!!!!!!!!!");
                        
                    } else {
                        
#if defined(P2PONTIPS)
#else
                        //                        [self updatePushViewAndLog:camera_ type:s->event time:eventTime];
#endif
                        
                    }
                    
                    
                }
                else if (IOTYPE_USER_IPCAM_DEVICE_USER_EVENT_REPORT == type)
                {
                    //if()
                    {
                        SMsgAVIoctrlUserEvent *s = (SMsgAVIoctrlUserEvent *)data;
                        NSInteger eventType = s->event;
                        NSLog(@"eventType:%ld", (long)eventType);
                        NSUInteger eventTime = s->time;
                        NSLog(@"eventTime:%ld", (long)eventTime);
                        //NSString *eventAlias = [NSString stringWithFormat:@"",];
                        
                        NSString *picn = [NSString stringWithUTF8String:(char *)s->pic_name];
                        NSString *alias = [NSString stringWithUTF8String:(char *)s->event_device_name];
                        NSString *devid = [NSString stringWithUTF8String:(char *)s->key_id];
                        
                        if (!picn) {
                            picn = [NSString stringWithFormat:@"%@", @""];
                        }
                        if (!alias) {
                            alias = [NSString stringWithFormat:@"%@", @""];
                        }
                        if (!devid) {
                            devid = [NSString stringWithFormat:@"%@", @""];
                        }
                        NSLog(@"picn:%@, alias:%@, devid:%@", picn, alias, devid);
                        
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU) || defined(P2PWEXVS) || defined(P2PPETWANT) || defined(P2PVIDEODB) || defined(P2PAUROCAM_WEX)
                        NSLog(@"camera_.isPushMode:%ld", (long)camera_.isPushMode);
                        
                        if (1 != camera_.isPushMode) {
                            NSLog(@"!!!!!!!!!!!!! No Push Mode !!!!!!!!!!!!!");
                            return;
                        }
#endif
                        if ([self checkIsSameEventForTime:eventTime type:eventType camera:camera_]) {
                            NSLog(@"!!!!!!!!!!!!! SAME EVENT !!!!!!!!!!!!!");
                            
                        } else {
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU)|| defined(P2PWEXVS) || defined(P2PVIDEODB) || defined(P2PAUROCAM_WEX)
                            [self showAlarmDialog:camera_ type:eventType time:eventTime picn:picn alias:alias devid:devid];
#endif
                        }
                        
#if defined(P2PONTIPS)
                        
                        NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
                        NSString *tmpNotificationStatus = [defaults objectForKey:@"notification_status"];
                        NSLog(@"AppDelegate  tmpNotificationStatus:%@", tmpNotificationStatus);
                        if (tmpNotificationStatus == nil ||
                            [tmpNotificationStatus isEqualToString:@""] ||
                            [tmpNotificationStatus isEqualToString:@"yes"]) {
                            
                            
                        } else {
                            return;
                        }
                        
                        NSLog(@"AppDelegate  eventType:%lx", (long)eventType);
                        
                        
                        NSString *info = @"";
                        
                        if (USER_EVENT_WARING_BLUE_BOOTTH == eventType) {
                            
                            NSLog(@"USER_EVENT_WARING_BLUE_BOOTTH  eventType:%lx", (long)eventType);
                            
                            SMsgAVIoctrlLongUserEvent *ss = (SMsgAVIoctrlLongUserEvent *)data;
                            
                            info = [NSString stringWithFormat:@"%s", ss->alarm_info];
                            
                        }
                        
                        NSLog(@"isShowAlarmTipView:%d", isShowAlarmTipView);
                        
                        if (YES == isShowAlarmTipView) {
                            return;
                        }
                        
                        [self.alarmTipView setHidden:NO];
                        
                        isShowAlarmTipView = YES;
                        
                        [self.alarmTipView startTimingStatus];
                        [self.alarmTipView alarmTipViewShow];
                        
                        
                        self.alarmTipView.devUid = camera_.uid;
                        self.alarmTipView.eventInfo = info;
                        self.alarmTipView.eventTime = eventTime;
                        self.alarmTipView.eventType = eventType;
                        
                        [self.alarmTipView updateStatusToView];
#endif
                        
                        
                    }
                } else if(type == IOTYPE_USER_IPCAM_DEVINFO_RESP) {
                    
                    SMsgAVIoctrlDeviceInfoResp *structDevInfo = (SMsgAVIoctrlDeviceInfoResp*)data;
                    
                    camera_.newVersionFlag = structDevInfo->reserved[7];
                    
                    NSLog(@"camera_.uid:%@, camera_.newVersionFlag:%ld", camera_.uid, (long)camera_.newVersionFlag);
                    
                    if (2 == camera_.newVersionFlag ||
                        3 == camera_.newVersionFlag) {
                        
                        camera_.isReadNewVersionFlag = 0;
                        
                        NSArray *keys = [NSArray arrayWithObjects:@"uid", nil];
                        NSArray *objects = [NSArray arrayWithObjects:camera_.uid, nil];
                        NSDictionary *dic = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationTotableViewReloadData" object:self userInfo:dic];
                        /*
                         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                         
                         [self getDeviceUpgradeInfo];
                         
                         });
                         */
                    } else {
                        
                    }
                    
                } else if(type == IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP) {
                    SmsgAVIoctrlEditAllDevicesResp *s = (SmsgAVIoctrlEditAllDevicesResp*)data;
                    NSLog(@"IOTYPE_USER_IPCAM_433_EDITDIVICES_LIST_RESP s->result_:%d, s->type:%d, s->alarm_type:%d, s->devices_.num_:%d", s->result, s->type, s->alarm_type, s->devices_.num_);
                    
                    if (0 == s->result) {
                        if (EDIT_433_LIST_TYPE_GET_ALARM_INFO == s->type) {
                            NSInteger num = s->devices_.num_;
                            
                            camera_.orgModeValue1 = s->alarm_type;
                            camera_.newModeValue1 = camera_.orgModeValue1;
                            
                            
                            [camera_.externalDeviceListArr removeAllObjects];
                            
                            for (int i=0; i<num; i++) {
                                
                                /*
                                 Alarm433Device *dev = [[Alarm433Device alloc] init];
                                 dev.key = [NSString stringWithUTF8String:s->devices_.devices_array_[i].key_];
                                 dev.alias = [NSString stringWithUTF8String:s->devices_.devices_array_[i].aliase_];
                                 
                                 dev.device_type = s->devices_.devices_array_[i].device_type_;
                                 dev.device_vender = s->devices_.devices_array_[i].device_vender_;
                                 
                                 #if defined(BUILD_FOR_GANSU_CAM)
                                 dev.device_alarmed = s->devices_.devices_array_[i].device_alarmed;
                                 dev.alarm_ptz_preset = s->devices_.devices_array_[i].alarm_ptz_preset;
                                 dev.device_closed = s->devices_.devices_array_[i].device_closed;
                                 #endif
                                 
                                 dev.new_device_alarmed = dev.device_alarmed;
                                 dev.new_alarm_ptz_preset = dev.alarm_ptz_preset;
                                 dev.new_device_closed = dev.device_closed;
                                 
                                 
                                 [camera_.externalDeviceListArr addObject:dev];
                                 
                                 NSLog(@"i:%d dev.alias:%@, dev.key:%@", i, dev.alias, dev.key);
                                 NSLog(@"dev.device_type:%ld, dev.device_vender:%ld, dev.device_alarmed:%ld, dev.alarm_ptz_preset:%ld, dev.device_closed:%ld", (long)dev.device_type, (long)dev.device_vender, (long)dev.device_alarmed, (long)dev.alarm_ptz_preset, (long)dev.device_closed);
                                 */
                            }
                            
                            NSArray *keys = [NSArray arrayWithObjects:@"uid", nil];
                            NSArray *objects = [NSArray arrayWithObjects:camera_.uid, nil];
                            NSDictionary *dic = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationTotableViewReloadData" object:self userInfo:dic];
                            
                            
                        }
                    } else {
                    }
                    
                    
                } else if(type == IOTYPE_USER_IPCAM_SET_UPGRADEONLIN_RESP) {
                    SMsgAVIoctrlUpgradeOnlineResp2 *s = (SMsgAVIoctrlUpgradeOnlineResp2*)data;
                    NSLog(@"IOTYPE_USER_IPCAM_SET_UPGRADEONLIN_RESP s->result_:%d, s->type:%d", s->result, s->type);
                    
                    if (UPGRADE_ONLINE_TYPE_GET_NOTES_PATH == s->type) {
                        NSLog(@"s->version_realease_notes:%s", s->version_realease_notes);
                        
                        
#if defined(SYNC_REMOTE_SERVER)
                        NSString *note = [NSString stringWithFormat:@"%s", s->version_realease_notes];
                        if (([note rangeOfString:@"nex"].location != NSNotFound)) {
                            
                            [self sendMsgToGetPushAddrFromDevice:camera_];
                        }
#endif
                        
                    }
                    
                } else if (type == IOTYPE_USER_IPCAM_PUSHSERVER_ADDR_SETTING_RESP) {
                    SMsgAVIoctrlPushserverAddrResp *s = (SMsgAVIoctrlPushserverAddrResp*)data;
                    
                    NSLog(@" s->command_type:%d  s->result:%d", s->command_type, s->result);
                    
                    // 0-get  1-set
                    if (s->command_type == 0) {
                        
                        if (0 == s->result) {
                            NSString *ip = [NSString stringWithFormat:@"%s", s->ip_addrs];
                            NSUInteger port = s->ip_port;
                            NSString *dir = [NSString stringWithFormat:@"%s", s->server_push_path];
                            
                            NSLog(@"IOTYPE_USER_IPCAM_PUSHSERVER_ADDR_SETTING_RESP ip:%@ port:%lu dir:%@",ip, (unsigned long)port, dir);
                            
                            
                            dispatch_queue_t queue = dispatch_queue_create("set_server_addr", NULL);
                            dispatch_async(queue, ^{
                                
                                NSLog(@"set_server_addr begin dispatch_get_main_queue!");
                                
                                /*         for (int i=0; i<100; i++) {
                                 
                                 if (nil == server_addr ||
                                 0 == server_port ||
                                 nil == server_addr_dir ||
                                 [server_addr isEqualToString:@""] ||
                                 [server_addr_dir isEqualToString:@""]) {
                                 
                                 } else {
                                 
                                 if ([ip isEqualToString:server_addr] &&
                                 (server_port == port) &&
                                 [dir isEqualToString:server_addr_dir]) {
                                 NSLog(@"addr all same");
                                 } else
                                 {
                                 #if defined(SYNC_REMOTE_SERVER)
                                 [self sendMsgToSetPushAddrFromDevice:camera_ addr:server_addr port:server_port dir:server_addr_dir];
                                 #endif
                                 
                                 }
                                 
                                 break;
                                 }
                                 
                                 NSLog(@"i:%d    server_addr:%@, server_port:%lu, server_addr_dir:%@", i, server_addr, (unsigned long)server_port, server_addr_dir);
                                 usleep(1000*1000);
                                 }
                                 
                                 */
                                
                                NSLog(@"set_server_addr over!");
                                
                            });
                            
                            
                        }
                        
                    } else {
                        
                    }
                    
                    
                }
                
            }
            
            - (void)showAlarmDialog:(MyCamera *)camera type:(NSInteger)type time:(NSUInteger)time picn:(NSString *)picn
        alias:(NSString *)alias devid:(NSString *)devid {
            
#if defined(P2PVIDEODB)
#else
            //   [[[[_rootViewController tabBar] items] objectAtIndex:1] setBadgeValue:@"!"];
#endif
            
            [camera setRemoteNotification:type EventTime:time];
            
            
            NSString *device_uid = camera.uid;
            
            if (nil == device_uid ||
                [device_uid isEqualToString:@""]) {
                device_uid = camera.deviceID;
            }
            
            if (self.database != NULL) {
                if (![self.database executeUpdate:@"INSERT INTO event(dev_uid, event_type, event_time) VALUES(?,?,?)", device_uid, [NSNumber numberWithInteger:type], [NSNumber numberWithUnsignedInteger:time]]) {
                    NSLog(@"Fail to add event to database.");
                }
            }
            
            
            if (USER_EVENT_ALARM_ARMED == type ||
                USER_EVENT_ALARM_DISARM == type ||
                USER_EVENT_SAFEBOX_DOOR_OPENED == type ||
                USER_EVENT_SAFEBOX_P2P_ONLIE == type ||
                USER_EVENT_SAFEBOX_P2P_OFFLINE == type
                ) {
            }
            else
            {
#if defined(P2PMENBOSHI) || defined(P2PBANDIANGOU)|| defined(P2PWEXVS) || defined(P2PAUROCAM_WEX)
                
                NSString *newalias = @"";
                
                if (USER_EVENT_MOTIONDECT == type ||
                    USER_EVENT_SAFEBOX_DOOR_ERROR == type ||
                    USER_EVENT_SAFEBOX_HOSTAGE == type) {
                    
                    newalias = [NSString stringWithFormat:@"%@", camera.name];
                    
                } else {
                    if (alias == nil || [alias isEqualToString:@""]) {
                        newalias = [NSString stringWithFormat:@"%@", camera.name];
                    } else {
                        newalias = alias;
                    }
                }
                
                
                
                camera.currentEventType = type;
                camera.currentEventTime = time;
                
                
                VisitingMessageViewController *visMessageViewController = [[VisitingMessageViewController alloc] initWithNibName:@"VisitingMessageViewController" bundle:nil];
                
                
                
                
                if (device_uid)
                    visMessageViewController.uidUserInfo = [[NSString alloc] initWithString:device_uid];
                else
                    visMessageViewController.uidUserInfo = @"";
                
                visMessageViewController.typeUserInfo = type;
                visMessageViewController.timeUserInfo = time;
                
                if (picn) {
                    visMessageViewController.picnUserInfo = [[NSString alloc] initWithString:picn];
                } else {
                    visMessageViewController.picnUserInfo = @"";
                }
                
                if (newalias)
                    visMessageViewController.aliasUserInfo = [[NSString alloc] initWithString:newalias];
                else
                    visMessageViewController.aliasUserInfo = @"";
                
                if (devid)
                    visMessageViewController.devidUserInfo = [[NSString alloc] initWithString:devid];
                else
                    visMessageViewController.devidUserInfo = @"";
                
                visMessageViewController.hidesBottomBarWhenPushed = YES;
                [self.window.rootViewController presentModalViewController:visMessageViewController animated:NO];
                
#elif defined(P2PVIDEODB)
                NSArray *keys=[NSArray arrayWithObjects:@"uid", nil];
                NSArray *objects=[NSArray arrayWithObjects:camera.uid, nil];
                NSDictionary *dic=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"GetPushNotification" object:self userInfo:dic];
                
                
#endif
            }
            
        }
            
            
            
            
            
            - (BOOL)checkIsSameEventForTime:(NSUInteger)time type:(NSInteger)type camera:(MyCamera *)camera {
                
                NSString *device_uid = camera.uid;
                
                if (nil == device_uid ||
                    [device_uid isEqualToString:@""]) {
                    device_uid = camera.deviceID;
                }
                
                NSLog(@"checkIsSameEventForTime  device_uid:%@, type:%ld, time:%lu", device_uid, (long)type, (unsigned long)time);
                
                BOOL isSame = NO;
                
                // 3 days
                NSUInteger findTime = time - (60*60*24*3);
                //NSUInteger findTime = time - (60);
                NSLog(@"findTime:%lu", (unsigned long)findTime);
                
#if defined(P2PPETWANT)
                FMResultSet *rs = [database executeQuery:@"SELECT * FROM eventpw WHERE dev_uid=? AND event_type=? AND event_time>=?", device_uid, [NSNumber numberWithInteger:type], [NSNumber numberWithUnsignedInteger:findTime]];
#else
                FMResultSet *rs = [self.database executeQuery:@"SELECT * FROM event WHERE dev_uid=? AND event_type=? AND event_time>=?", device_uid, [NSNumber numberWithInteger:type], [NSNumber numberWithUnsignedInteger:findTime]];
#endif
                
                while([rs next]) {
                    NSUInteger eventTime = [rs doubleForColumn:@"event_time"];
                    //NSLog(@"DB-event-event_time:%ld", (long)eventTime);
                    
                    if (eventTime == time) {
                        isSame = YES;
                        break;
                    }
                }
                [rs close];
                
                return isSame;
            }
            
            - (BOOL)checkIsSameEventForTime:(NSUInteger)time type:(NSInteger)type uid:(NSString *)uid {
                NSLog(@"checkIsSameEventForTime  uid:%@, type:%ld, time:%lu", uid, (long)type, (unsigned long)time);
                
                BOOL isSame = NO;
                
                // 3 days
                NSUInteger findTime = time - (60*60*24*3);
                //NSUInteger findTime = time - (60);
                NSLog(@"findTime:%lu", (unsigned long)findTime);
                
#if defined(P2PPETWANT)
                FMResultSet *rs = [database executeQuery:@"SELECT * FROM eventpw WHERE dev_uid=? AND event_type=? AND event_time>=?", uid, [NSNumber numberWithInteger:type], [NSNumber numberWithUnsignedInteger:findTime]];
#else
                FMResultSet *rs = [self.database executeQuery:@"SELECT * FROM event WHERE dev_uid=? AND event_type=? AND event_time>=?", uid, [NSNumber numberWithInteger:type], [NSNumber numberWithUnsignedInteger:findTime]];
#endif
                
                while([rs next]) {
                    NSUInteger eventTime = [rs doubleForColumn:@"event_time"];
                    //NSLog(@"DB-event-event_time:%ld", (long)eventTime);
                    
                    if (eventTime == time) {
                        isSame = YES;
                        break;
                    }
                }
                [rs close];
                
                return isSame;
            }
            
            
            
            
#pragma mark - 配置部分
            
            + (NSString *) pathForDocumentsResource:(NSString *) relativePath
            {
                static NSString* documentsPath = nil;
                
                if (nil == documentsPath) {
                    
                    NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    documentsPath = [dirs objectAtIndex:0];
                }
                
                return [documentsPath stringByAppendingPathComponent:relativePath];
            }
            
            - (NSString *) pathForDocumentsResource:(NSString
                                                     *) relativePath {
                
                static NSString* documentsPath = nil;
                
                if (nil == documentsPath) {
                    
                    NSArray* dirs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    documentsPath = [dirs objectAtIndex:0] ;
                }
                
                return [documentsPath stringByAppendingPathComponent:relativePath];
            }
            
            
            
            - (void)saveImageToFile:(UIImage *)image :(NSString *)fileName {
                
                NSData *imgData = UIImageJPEGRepresentation(image, 1.0f);
                NSString *imgFullName = [self pathForDocumentsResource:fileName];
                
                [imgData writeToFile:imgFullName atomically:YES];
            }
            
            
            - (void)sendMsgToGetDeviceFlageFromDevice:(MyCamera *)camera {
                SMsgAVIoctrlSetUpgradeOnlineReq *req = (SMsgAVIoctrlSetUpgradeOnlineReq *) malloc(sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
                memset(req, 0, sizeof(SMsgAVIoctrlSetUpgradeOnlineReq));
                
                req->type = UPGRADE_ONLINE_TYPE_GET_NOTES_PATH;
                
                [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_SET_UPGRDEONLIN_REQ Data:(char *)req DataSize:sizeof(SMsgAVIoctrlSetUpgradeOnlineReq)];
                
                free(req);
                
                NSLog(@"sendMsgToGetDeviceFlageFromDevice  camera.uid:%@", camera.uid);
            }
            
            - (void)sendMsgToGetPushAddrFromDevice:(MyCamera *)camera {
                SMsgAVIoctrlPushserverAddrReq *req = (SMsgAVIoctrlPushserverAddrReq *) malloc(sizeof(SMsgAVIoctrlPushserverAddrReq));
                memset(req, 0, sizeof(SMsgAVIoctrlPushserverAddrReq));
                
                req->command_type = 0;
                
                [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_PUSHSERVER_ADDR_SETTING_REQ Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPushserverAddrReq)];
                
                free(req);
                
                NSLog(@"sendMsgToGetPushAddrFromDevice  camera.uid:%@", camera.uid);
                
            }
            
            - (void)sendMsgToSetPushAddrFromDevice:(MyCamera *)camera addr:(NSString *)ip port:(NSUInteger)port  dir:(NSString *)dir {
                
                SMsgAVIoctrlPushserverAddrReq *req = (SMsgAVIoctrlPushserverAddrReq *) malloc(sizeof(SMsgAVIoctrlPushserverAddrReq));
                memset(req, 0, sizeof(SMsgAVIoctrlPushserverAddrReq));
                
                req->command_type = 1;
                
                memcpy(req->ip_addrs, [ip UTF8String], sizeof(req->ip_addrs));
                
                req->ip_port = (unsigned int)port;
                
                memcpy(req->server_push_path, [dir UTF8String], sizeof(req->server_push_path));
                
                NSLog(@"sendMsgToSetPushAddrFromDevice req->ip_addrs:%s req->ip_port:%d req->server_push_path:%s",req->ip_addrs, req->ip_port, req->server_push_path);
                
                [camera sendIOCtrlToChannel:0 Type:IOTYPE_USER_IPCAM_PUSHSERVER_ADDR_SETTING_REQ Data:(char *)req DataSize:sizeof(SMsgAVIoctrlPushserverAddrReq)];
                
                free(req);
            }
            
#if defined(ACCOUNT_MODE)
            
            - (void)syncAllLocalDeviceToServer {
            }
            
            
            - (void)syncServerToLocal {
                
                f (self.database != NULL) {
                    
                    NSMutableArray *cameralist = [[NSMutableArray alloc] init];
                    NSMutableArray *cameraInsertList = [[NSMutableArray alloc] init];
                    NSMutableArray *cameraUpdateList = [[NSMutableArray alloc] init];
                    
                    
                    FMResultSet *rs = [database executeQuery:@"SELECT * FROM device2"];
                    
                    int cnt = 0;
                    
                    while([rs next] && cnt++ < MAX_CAMERA_LIMIT) {
                        
                        NSString *uid = [rs stringForColumn:@"dev_uid"];
                        NSString *name = [rs stringForColumn:@"dev_nickname"];
                        NSString *view_acc = [rs stringForColumn:@"view_acc"];
                        NSString *view_pwd = [rs stringForColumn:@"view_pwd"];
                        NSInteger channel = [rs intForColumn:@"channel"];
                        NSString *dev_type = [rs stringForColumn:@"dev_type"];
                        NSInteger is_add_server_success = [rs intForColumn:@"is_add_server_success"];
                        
                        MyCamera *cam = [[MyCamera alloc] initWithName:name viewAccount:view_acc viewPassword:view_pwd];
                        [cam setLastChannel:channel];
                        
                        cam.deviceID = uid;
                        
                        cam.deviceType = dev_type;
                        //camera.isPushMode = [pushallowed isEqualToString:@"yes"] ? 1 : 0;
                        
                        cam.isAddServerSuccess = is_add_server_success;
                        
                        if (cam.isAddServerSuccess == 0) {
                            cam.isPushMode = 1;
                        }
                        
                        NSLog(@"syncServerToLocal uid:%@  camera.name:%@, camera.viewPwd:%@, cam.isAddServerSuccess:%ld", uid, cam.name, cam.viewPwd, (long)cam.isAddServerSuccess);
                        
                        
                        [cameralist addObject:cam];
                    }
                    
                    [rs close];
                    
                    
                    for (int i=0; i<[self.camera_list count]; i++) {
                        MyCamera *cam = (MyCamera *)[self.camera_list objectAtIndex:i];
                        
                        cam.isAddServerSuccess = YES;
                        
                        BOOL isFind = NO;
                        for (int j=0; j<[cameralist count]; j++) {
                            MyCamera *cam2 = (MyCamera *)[cameralist objectAtIndex:j];
                            
                            if ([cam.deviceID isEqualToString:cam2.deviceID]) {
                                isFind = YES;
                                break;
                            }
                        }
                        
                        if (isFind) {
                            [cameraUpdateList addObject:cam];
                        } else {
                            [cameraInsertList addObject:cam];
                        }
                        
                    }
                    
                    
                    NSLog(@"[cameraUpdateList count]:%lu", (unsigned long)[cameraUpdateList count]);
                    NSLog(@"[cameraInsertList count]:%lu", (unsigned long)[cameraInsertList count]);
                    
                    
                    // update local device
                    for (int i=0; i<[cameraUpdateList count]; i++) {
                        MyCamera *cam = (MyCamera *)[cameraUpdateList objectAtIndex:i];
                        
                        if (![database executeUpdate:@"UPDATE device2 SET dev_nickname=?, view_pwd=?, channel=?, dev_type=?, is_add_server_success=? WHERE dev_uid=?", cam.name, cam.viewPwd, cam.lastChannel, cam.deviceType, cam.isAddServerSuccess, cam.deviceID]) {
                            NSLog(@"Fail to update device2 to database.");
                        }
                        
                    }
                    
                    // insert local device
                    for (int i=0; i<[cameraUpdateList count]; i++) {
                        MyCamera *cam = (MyCamera *)[cameraUpdateList objectAtIndex:i];
                        
                        [database executeUpdate:@"INSERT INTO device2(dev_uid, dev_nickname, dev_name, dev_pwd, view_acc, view_pwd, channel, dev_type, is_add_server_success) VALUES(?,?,?,?,?,?,?,?,?)",
                         cam.deviceID, cam.name, cam.name, cam.viewPwd, cam.viewAcc, cam.viewPwd, cam.lastChannel, cam.deviceType, cam.isAddServerSuccess];
                    }
                }
            }
            
            - (void)syncNewLocalDeviceToServer {
                if (self.database != NULL) {
                    
                    NSMutableArray *cameralist = [[NSMutableArray alloc] init];
                    
                    FMResultSet *rs = [database executeQuery:@"SELECT * FROM device2"];
                    
                    int cnt = 0;
                    
                    while([rs next] && cnt++ < MAX_CAMERA_LIMIT) {
                        
                        NSString *uid = [rs stringForColumn:@"dev_uid"];
                        NSString *name = [rs stringForColumn:@"dev_nickname"];
                        NSString *view_acc = [rs stringForColumn:@"view_acc"];
                        NSString *view_pwd = [rs stringForColumn:@"view_pwd"];
                        NSInteger channel = [rs intForColumn:@"channel"];
                        NSString *dev_type = [rs stringForColumn:@"dev_type"];
                        NSInteger is_add_server_success = [rs intForColumn:@"is_add_server_success"];
                        
                        MyCamera *cam = [[MyCamera alloc] initWithName:name viewAccount:view_acc viewPassword:view_pwd];
                        [cam setLastChannel:channel];
                        
                        cam.deviceID = uid;
                        
                        cam.deviceType = dev_type;
                        //camera.isPushMode = [pushallowed isEqualToString:@"yes"] ? 1 : 0;
                        
                        cam.isAddServerSuccess = is_add_server_success;
                        
                        if (cam.isAddServerSuccess == 0) {
                            cam.isPushMode = 1;
                        }
                        
                        NSLog(@"syncNewLocalDeviceToServer uid:%@  camera.name:%@, camera.viewPwd:%@, cam.isAddServerSuccess:%ld", uid, cam.name, cam.viewPwd, (long)cam.isAddServerSuccess);
                        
                        [cameralist addObject:cam];
                    }
                    
                    [rs close];
                    
                    
                    for (int i=0; i<[cameralist count]; i++) {
                        
                        MyCamera *cam = (MyCamera *)[cameralist objectAtIndex:i];
                        
                        if (cam.isAddServerSuccess == 0) {
                            MyCamera *camera0 = [[MyCamera alloc] initWithName:cam.name viewAccount:cam.viewAcc viewPassword:cam.viewPwd];
                            [camera0 setLastChannel:cam.lastChannel];
                            
                            camera0.deviceType = cam.deviceType;
                            camera0.isPushMode = cam.isPushMode;
                            
                            NSLog(@"-------------------------------------------------------- cam.isAddServerSuccess == 0 ; cam.deviceID:%@, camera.name:%@, camera.viewPwd:%@", cam.deviceID, cam.name, cam.viewPwd);
                            
                            BOOL isFindSameDevice = NO;
                            for (int i=0; i<[self.camera_list count]; i++) {
                                //MyCamera *cam0 = (MyCamera *)[self.camera_list objectAtIndex:i];
                                NSString *devid = (NSString *)[self.camera_uid_list objectAtIndex:i];
                                
                                
                                if ([devid isEqualToString:cam.deviceID]) {
                                    
                                    isFindSameDevice = YES;
                                    
                                    break;
                                }
                                
                            }
                            
                            NSLog(@"isFindSameDevice:%d", isFindSameDevice);
                            
                            if (isFindSameDevice) {
                                
                            } else {
                                [self.camera_list addObject:camera0];
                                if (cam.deviceID)
                                    [self.camera_uid_list addObject:cam.deviceID];
                                
                            }
                            
                            // syncToServer
                            dispatch_queue_t queue = dispatch_queue_create("sync_to_server", NULL);
                            dispatch_async(queue, ^{
                                
                                NSLog(@" sync_to_server dispatch_queue_create!");
                                
                                for (int i=0;;i++) {
                                    
                                    BOOL isSuccess = [self syncToServer:cam];
                                    if (isSuccess) {
                                        NSLog(@"++++++++++++++ syncToServer  success!!!!!!!!!!!  i=%d", i);
                                        break;
                                    } else {
                                        NSLog(@"============== syncToServer  fail!!!!!!!!!!!  i=%d", i);
                                        usleep(3*1000*1000);
                                    }
                                }
                                
                                NSLog(@" sync_to_server over!");
                                
                            });
                            dispatch_release(queue);
                        }
                        
                    }
                    
                }
                
            }
            
            
            - (BOOL)syncToServer:(MyCamera *)cam {
                NSString *servercmd = @"";
                NSString *servercode = @"";
                NSString *servermsg = @"";
                
#if defined(P2PWEXVS)
                
                NSString *param = [NSString stringWithFormat:@"cmd=adddev&mode=%@&platform=%@&userid=%@&devid=%@&devuser=%@&devpw=%@&devconn=%@&devchnl=%@&devstream=%@&devalias=%@&devtype=%@&scode=%@&appn=%@",
                                   @"normal", loginPlatform, loginAccount, cam.deviceID, @"admin", cam.viewPwd, @"p2p", @"00", @"main", cam.name, cam.deviceType, loginSecurityCode, XG_APPN_STR];
#else
                NSString *param = [NSString stringWithFormat:@"cmd=adddev&mode=%@&platform=%@&userid=%@&devid=%@&devuser=%@&devpw=%@&devconn=%@&devchnl=%@&devstream=%@&devalias=%@&scode=%@&appn=%@",
                                   @"normal", loginPlatform, loginAccount, cam.deviceID, @"admin", cam.viewPwd, @"p2p", @"00", @"main", cam.name, loginSecurityCode, XG_APPN_STR];
#endif
                
                NSString *cmd = [NSString stringWithFormat:@"%@%@", LOGIN_MODE_SERVER_ADDR, param];
                NSLog(@"cmd:%@", cmd);
                NSString *dataUTF8 = [cmd stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSLog(@"dataUTF8:%@", dataUTF8);
                cmd = dataUTF8;
                
                CommonHttp *commonHttp0 = [[CommonHttp alloc] init];
                
                NSData *recervedData = [commonHttp0 reqHttpGetMode:cmd];
                
                if (recervedData) {
                    NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:recervedData options:0 error:nil];
                    
                    servercmd = [jsonData objectForKey:@"cmd"];
                    servercode = [jsonData objectForKey:@"code"];
                    servermsg = [jsonData objectForKey:@"msg"];
                    
                    NSLog(@"cmd=%@ code=%@, msg=%@", servercmd, servercode, servermsg);
                    
                } else {
                    NSLog(@"recervedData == nil");
                    
                    /*
                     [self alertTipNetwork];
                     
                     usleep(3 * 1000 *1000);
                     */
                    
                    //[camera release];
                    
                    ////continue;
                }
                
                BOOL isAddServerSucc = NO;
                
                if (![commonHttp0 retValueShow:[servercmd intValue] code:[servercode intValue]]) {
                    
                    /*
                     usleep(3 * 1000 *1000);
                     */
                    
                    //[camera release];
                    
                    ////continue;
                    
                    
                    int RET_ADDDEV_DEVID_TOKEN        = 21902; //设备已被添加
                    int RET_ADDDEV_ADDED              = 21903; //设备已在账号名下
                    if ([servercode intValue] == RET_ADDDEV_DEVID_TOKEN ||
                        [servercode intValue] == RET_ADDDEV_ADDED) {
                        isAddServerSucc = YES;
                    }
                    
                    
                } else {
                    
                    isAddServerSucc = YES;
                    
                    // get newuser or olduser
                    if ([servermsg isEqualToString:@"newuser"]) {
                    }
                    
                }
                
                [commonHttp0 release];
                
                
                NSLog(@"isAddServerSuccOK:%d  cam.deviceID:%@", isAddServerSucc, cam.deviceID);
                if (isAddServerSucc) {
                    cam.isAddServerSuccess = 1;
                    
                    // update self.camera_list
                    for (int i=0; i<[self.camera_list count]; i++) {
                        MyCamera *cam0 = (MyCamera *)[self.camera_list objectAtIndex:i];
                        NSString *devid = (NSString *)[self.camera_uid_list objectAtIndex:i];
                        
                        
                        if ([devid isEqualToString:cam.deviceID]) {
                            
                            cam0 = cam.isAddServerSuccess;
                            
                            break;
                        }
                        
                    }
                    
                    // update device2
                    if (![database executeUpdate:@"UPDATE device2 SET is_add_server_success=? WHERE dev_uid=?",  [NSNumber numberWithInt:cam.isAddServerSuccess], cam.deviceID]) {
                        NSLog(@"Fail to update device2 to database.");
                    }
                    
                }
                
                
                return isAddServerSucc;
            }
            
            
            
            - (void)GetSyncNewDeviceToServerNotification:(NSNotification*)notification {
                NSLog(@"<<<<<<------ GetSyncNewDeviceToServerNotification ------>>>>>>");
                
                [self syncNewLocalDeviceToServer];
                
            }
            
#endif
            
#pragma mark - Core Data Saving support
            
            - (void)saveContext {
                NSManagedObjectContext *context = self.persistentContainer.viewContext;
                NSError *error = nil;
                if ([context hasChanges] && ![context save:&error]) {
                    // Replace this implementation with code to handle the error appropriately.
                    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    NSLog(@"Unresolved error %@, %@", error, error.userInfo);
                    abort();
                }
            }
            
            @end
